package com.ruoyi.quality.service.impl;


import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ruoyi.baseData.domain.Material;
import com.ruoyi.baseData.domain.MaterialType;
import com.ruoyi.baseData.mapper.MaterialMapper;
import com.ruoyi.baseData.mapper.MaterialTypeMapper;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.quality.domain.*;
import com.ruoyi.quality.domain.dto.InspectionTaskDto;
import com.ruoyi.quality.domain.vo.InspectionTemplateItemVo;
import com.ruoyi.quality.mapper.*;
import com.sun.corba.se.impl.protocol.INSServerRequestDispatcher;
import io.swagger.v3.oas.models.security.SecurityScheme;
import lombok.Data;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 质检任务查询算法
 */
public class InspectionTaskCheck {

    /**
     * 最终报错
     */
    public String MSG = "OK";

    /**
     * 物料类型配置MAP
     */
    private MaterialTypeMapper materialTypeMapper;


//    private MaterialMapper materialMapper;

    /**
     * 抽样MAP
     */
    private SamplingMapper samplingMapper;

    /**
     * 抽样项的数据
     */
    private SamplingItemMapper samplingItemMapper;

    /**
     * 抽样模板项目
     */
    private InspectionTemplateMapper inspectionTemplateMapper;

    /**
     * 质检模板项目配置接口
     */
    private InspectionTemplateItemMapper inspectionTemplateItemMapper;

    /**
     * 质检任务
     */
    private InspectionTaskMapper inspectionTaskMapper;


    private InspectionTaskTemplateSamplingItemMapper inspectionTaskTemplateSamplingItemMapper;


    private InspectionTemplateMaterialMapper inspectionTemplateMaterialMapper;


    public Map<InspectionTask, List<InspectionTaskTemplateSamplingItem>> RESULT_MAP = new HashMap<>();


    public InspectionTaskCheck(

            MaterialTypeMapper materialTypeMapper,
            SamplingMapper samplingMapper,
            SamplingItemMapper samplingItemMapper,
            InspectionTemplateMapper inspectionTemplateMapper,
            InspectionTemplateItemMapper inspectionTemplateItemMapper,
            InspectionTaskMapper inspectionTaskMapper,
            InspectionTaskTemplateSamplingItemMapper inspectionTaskTemplateSamplingItemMapper,
            //物料质检模板
            InspectionTemplateMaterialMapper inspectionTemplateMaterialMapper

    ) {
        this.inspectionTemplateMaterialMapper = inspectionTemplateMaterialMapper;
        this.materialTypeMapper = materialTypeMapper;
        this.samplingMapper = samplingMapper;
        this.samplingItemMapper = samplingItemMapper;
        this.inspectionTemplateMapper = inspectionTemplateMapper;
        this.inspectionTemplateItemMapper = inspectionTemplateItemMapper;
        this.inspectionTaskMapper = inspectionTaskMapper;
        this.inspectionTaskTemplateSamplingItemMapper = inspectionTaskTemplateSamplingItemMapper;
        this.inspectionTemplateMaterialMapper = inspectionTemplateMaterialMapper;

    }

    public void initData(List<InspectionTaskDto> inspectionTaskDtos) {
        List<String> materialTypeCodes = new ArrayList<>();
        List<String> materialCodes = new ArrayList<>();
        /**
         * 获取前两位的编码
         */
        materialTypeCodes = inspectionTaskDtos.stream().map(item -> {
            String materialType = item.getMaterialCode().substring(0, 2);
            return materialType;
        }).collect(Collectors.toList());

        materialCodes = inspectionTaskDtos.stream().map(item -> {
            String materialType = item.getMaterialCode();
            return materialType;
        }).collect(Collectors.toList());

        /**
         * 查询物料类型(查询物料类型)
         */
        MPJLambdaWrapper<MaterialType> wrapper = new MPJLambdaWrapper<MaterialType>()
                .in(MaterialType::getCode, materialTypeCodes)
                .ne(MaterialType::getDelFlag, 1);
        List<MaterialType> materialTypes = materialTypeMapper.selectList(wrapper);

        //模板
//        if(null == materialTypes ||  materialTypes.size() <=0) {
//            MSG = "有"
//        }
        /**
         * 物料主数据修改
         */
        List<InspectionTemplateMaterial> inspectionTemplateMaterials = inspectionTemplateMaterialMapper.selectList(new MPJLambdaWrapper<InspectionTemplateMaterial>()
                .in(InspectionTemplateMaterial::getMaterialCode, materialCodes)
                .ne(InspectionTemplateMaterial::getDelFlag, 1)
        );
//        List<String> existMaterials = inspectionTemplateMaterials.stream().map(item -> item.getMaterialCode()).distinct().collect(Collectors.toList());
        /**
         *
         */
        StringBuffer sb = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        Set<Long> inspectionTmpIds = new HashSet<>(); //质检模板ID
        for(String materialCode: materialCodes) {
            Optional<InspectionTemplateMaterial> optionalInspectionTemplateMaterial
                    = inspectionTemplateMaterials.stream().filter(item ->materialCode.equals(item.getMaterialCode())).findFirst();

            Optional<MaterialType> optionalMaterialType
                    = materialTypes.stream().filter(item ->materialCode.substring(0, 2).equals(item.getCode())).findFirst();

            if(!optionalMaterialType.isPresent()) {
                sb2.append(materialCode.substring(0, 2) + ";");
            }


            if(optionalInspectionTemplateMaterial.isPresent()) {
                InspectionTemplateMaterial inspectionTemplateMaterial = optionalInspectionTemplateMaterial.get();
                if(null == inspectionTemplateMaterial.getInspectionTemplateId()) {
                    sb.append(materialCode + ";");
                } else {
                    inspectionTmpIds.add(inspectionTemplateMaterial.getInspectionTemplateId());
                }
            } else {
                sb.append(materialCode + ";");
            }
//            if(!existMaterials.contains(materialCode)) {
//
//            }
        }
        if(sb2.length() > 0) {
            MSG = sb2.toString() + "这些物料类型没有配置抽样周期";
            return;
        }
        if(sb.length()> 0) {
            MSG = sb.toString() + "这些物料没有配置模板";
            return;
        }

        Set<Long> samplingLabIds = new HashSet<>();
        Set<Long> samplingAppearanceIds = new HashSet<>();
        Set<Long> samplingPackageIds = new HashSet<>();
        Set<Long> samplingSizeIds = new HashSet<>();
        Set<Long> samplingInterfaceIds = new HashSet<>();
        Set<Long> samplingIds = new HashSet<>();
        for (MaterialType materialType : materialTypes) {
            /**
             * todo:该地方出错直接获取物料的质检模板
             */
//            inspectionTmpIds.add(materialType.getInspectionTemplateId()); //该质检模板不对
            samplingLabIds.add(materialType.getSamplingLabId());
            samplingAppearanceIds.add(materialType.getSamplingAppearanceId());
            samplingPackageIds.add(materialType.getSamplingPackageId());
            samplingSizeIds.add(materialType.getSamplingSizeId());
            samplingInterfaceIds.add(materialType.getSamplingInterfaceId());
        }
        samplingIds.addAll(samplingLabIds);
        samplingIds.addAll(samplingAppearanceIds);
        samplingIds.addAll(samplingPackageIds);
        samplingIds.addAll(samplingSizeIds);
        samplingIds.addAll(samplingInterfaceIds);
        /**
         * 质检模板和抽样方案(质检模板)
         */

//        inspectionTmpIds = inspectionTemplateMaterials.stream().map(item -> item.getInspectionTemplateId()).collect(Collectors.toSet());
//        StringBuffer sb = new StringBuffer();
//        for(InspectionTemplateMaterial inspectionTemplateMaterial : inspectionTemplateMaterials ) {
//            if(null == inspectionTemplateMaterial.getInspectionTemplateId()) {
//                sb.append(inspectionTemplateMaterial.getMaterialCode() + ";");
//            } else {
//                inspectionTmpIds.add(inspectionTemplateMaterial.getInspectionTemplateId());
//            }
//        }


//        List<InspectionTemplate> inspectionTemplates = new ArrayList<>();
        List<InspectionTemplateItemVo> inspectionTemplateItems = new ArrayList<>();
        if (null != inspectionTmpIds && inspectionTmpIds.size() > 0) {
//            inspectionTemplates = inspectionTemplateMapper.selectList(new MPJLambdaWrapper<InspectionTemplate>()
//                    .in(InspectionTemplate::getId, inspectionTmpIds)
//                    .ne(MaterialType::getDelFlag, 1));
            MPJLambdaWrapper<InspectionTemplateItem> wrapper2 = new MPJLambdaWrapper<InspectionTemplateItem>()
                    .selectAll(InspectionTemplateItem.class)//查询user表全部字段
                    .selectAs(InspectionItem::getFillQty, InspectionTemplateItemVo::getFillQty)
                    .selectAs(InspectionItem::getFillType, InspectionTemplateItemVo::getFillType)
                    .leftJoin(InspectionItem.class, on -> on.eq( InspectionItem::getId, InspectionTemplateItem::getInspectionItemId)
                            .eq(InspectionItem::getDelFlag, 0)
                    )
                    .in(InspectionTemplateItem::getInspectionTemplateId, inspectionTmpIds)
                    .ne(InspectionTemplateItem::getDelFlag, 1);
            inspectionTemplateItems = inspectionTemplateItemMapper.selectJoinList(InspectionTemplateItemVo.class, wrapper2);
        }
        /**
         * 抽样方案和抽样项
         */
        List<Sampling> samplings = new ArrayList<>();
        List<SamplingItem> samplingItems = new ArrayList<>();
        if (null != samplingIds && samplingIds.size() > 0) {
            samplings = samplingMapper.selectList(new MPJLambdaWrapper<Sampling>()
                    .in(Sampling::getId, samplingIds).ne(Sampling::getDelFlag, 1));
            samplingItems = samplingItemMapper.selectList(new MPJLambdaWrapper<SamplingItem>().in(SamplingItem::getSamplingId, samplingIds).ne(Sampling::getDelFlag, 1));
        }



        for (InspectionTaskDto inspectionTaskDto : inspectionTaskDtos) {

            String materialTypeCode = inspectionTaskDto.getMaterialCode().substring(0, 2); //物料类型
            Integer qty = inspectionTaskDto.getQty(); //数量

            /**
             * todo::根据物料获取质检方案
             * 根据物料分类获取抽样规则
             */
            Optional<MaterialType> optionalMaterialType = materialTypes.stream().filter(item -> item.getCode().equals(materialTypeCode)).findFirst();

            Optional<InspectionTemplateMaterial> optionalInspectionTemplateMaterial = inspectionTemplateMaterials.stream().filter(item -> item.getMaterialCode().equals(inspectionTaskDto.getMaterialCode())).findFirst();

            if (optionalMaterialType.isPresent() && optionalInspectionTemplateMaterial.isPresent()) {
                MaterialType materialType = optionalMaterialType.get();
                InspectionTemplateMaterial inspectionTemplateMaterial = optionalInspectionTemplateMaterial.get();
                /**
                 * 代码修改提交
                 */
                List<InspectionTemplateItemVo> inspectionTemplateItemList = inspectionTemplateItems.stream().filter(item -> item.getInspectionTemplateId().equals(inspectionTemplateMaterial.getInspectionTemplateId())).collect(Collectors.toList());
                Integer countLabQty = 1; //性能
                Integer countAppearanceQty = 1; //外观
                Integer countPackageQty = 1;
                Integer countSizeQty = 1;
                Integer countInterfaceQty = 1;
                countLabQty = getSamplingItemQty(samplingItems, qty, materialType.getSamplingLabId());
                countAppearanceQty = getSamplingItemQty(samplingItems, qty, materialType.getSamplingAppearanceId());
                countPackageQty = getSamplingItemQty(samplingItems, qty, materialType.getSamplingPackageId());
                countSizeQty = getSamplingItemQty(samplingItems, qty, materialType.getSamplingSizeId());
                countInterfaceQty = getSamplingItemQty(samplingItems, qty, materialType.getSamplingInterfaceId());

                String userName = SecurityUtils.getUsername();
                InspectionTask test2 = new InspectionTask();
                BeanUtils.copyProperties(inspectionTaskDto, test2, new String[]{"id"});
                test2.setStatus("待检");
                test2.setDelFlag(false);
                test2.setCreateBy(userName);
                test2.setCreateTime(new Date());
//                inspectionTaskMapper.insert(test2);

                List<InspectionTaskTemplateSamplingItem>  inspectionTaskTemplateSamplingItems = new ArrayList<>();

                for (InspectionTemplateItemVo inspectionTemplateItem : inspectionTemplateItemList) {
                    if ("性能".equals(inspectionTemplateItem.getFillType())) {
                        for (int i = 0; i < countLabQty; i++) {
                            Integer sequence = i + 1;
                            InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                            inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                            inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                            inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                            inspectionTaskTemplateSamplingItem.setSequence(sequence);
                            //增加抽样方案字段
                            inspectionTaskTemplateSamplingItem.setSamplingId(materialType.getSamplingLabId());
                            inspectionTaskTemplateSamplingItem.setDelFlag(false);
                            inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                            inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                            inspectionTaskTemplateSamplingItems.add(inspectionTaskTemplateSamplingItem);
//                            inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
                        }

                    } else if ("外观".equals(inspectionTemplateItem.getFillType())) {
                        for (int i = 0; i < countAppearanceQty; i++) {
                            Integer sequence = i + 1;
                            InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                            inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                            inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                            inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                            inspectionTaskTemplateSamplingItem.setSequence(sequence);
                            //增加抽样方案字段
                            inspectionTaskTemplateSamplingItem.setSamplingId(materialType.getSamplingAppearanceId());
                            inspectionTaskTemplateSamplingItem.setDelFlag(false);
                            inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                            inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                            inspectionTaskTemplateSamplingItems.add(inspectionTaskTemplateSamplingItem);
//                            inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
                        }

                    } else if ("包装及标识".equals(inspectionTemplateItem.getFillType())) {
                        for (int i = 0; i < countPackageQty; i++) {
                            Integer sequence = i + 1;
                            InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                            inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                            inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                            inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                            inspectionTaskTemplateSamplingItem.setSequence(sequence);
                            //增加抽样方案字段
                            inspectionTaskTemplateSamplingItem.setSamplingId(materialType.getSamplingPackageId());
                            inspectionTaskTemplateSamplingItem.setDelFlag(false);
                            inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                            inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                            inspectionTaskTemplateSamplingItems.add(inspectionTaskTemplateSamplingItem);
//                            inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
                        }

                    } else if ("尺寸".equals(inspectionTemplateItem.getFillType())) {
                        for (int i = 0; i < countSizeQty; i++) {
                            Integer sequence = i + 1;
                            InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                            inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                            inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                            inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                            inspectionTaskTemplateSamplingItem.setSequence(sequence);
                            //增加抽样方案字段
                            inspectionTaskTemplateSamplingItem.setSamplingId(materialType.getSamplingSizeId());
                            inspectionTaskTemplateSamplingItem.setDelFlag(false);
                            inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                            inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                            inspectionTaskTemplateSamplingItems.add(inspectionTaskTemplateSamplingItem);
//                            inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
                        }

                    } else if ("接口卷比例".equals(inspectionTemplateItem.getFillType())) {
                        for (int i = 0; i < countInterfaceQty; i++) {
                            Integer sequence = i + 1;
                            InspectionTaskTemplateSamplingItem inspectionTaskTemplateSamplingItem = new InspectionTaskTemplateSamplingItem();
                            inspectionTaskTemplateSamplingItem.setInspectionTaskId(test2.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateItemId(inspectionTemplateItem.getId());
                            inspectionTaskTemplateSamplingItem.setInspectionItemId(inspectionTemplateItem.getInspectionItemId());
                            inspectionTaskTemplateSamplingItem.setInspectionTemplateId(inspectionTemplateItem.getInspectionTemplateId());
                            inspectionTaskTemplateSamplingItem.setFillQty(inspectionTemplateItem.getFillQty());
                            inspectionTaskTemplateSamplingItem.setFillType(inspectionTemplateItem.getFillType());
                            inspectionTaskTemplateSamplingItem.setSequence(sequence);
                            //增加抽样方案字段
                            inspectionTaskTemplateSamplingItem.setSamplingId(materialType.getSamplingInterfaceId());
                            inspectionTaskTemplateSamplingItem.setDelFlag(false);
                            inspectionTaskTemplateSamplingItem.setCreateBy(userName);
                            inspectionTaskTemplateSamplingItem.setCreateTime(new Date());
                            inspectionTaskTemplateSamplingItems.add(inspectionTaskTemplateSamplingItem);
//                            inspectionTaskTemplateSamplingItemMapper.insert(inspectionTaskTemplateSamplingItem);
                        }

                    }
                }

                RESULT_MAP.put(test2, inspectionTaskTemplateSamplingItems);
            }
        }

    }


    private Integer getSamplingItemQty(List<SamplingItem> samplingItems, Integer materialQty, Long samplingId) {
        Integer qty = 1;
        Optional<SamplingItem> optionalSamplingItemLab = samplingItems.stream().filter(item ->
                item.getMinSize() < materialQty
                        && materialQty <= item.getMaxSize()
                        && item.getSamplingId() == samplingId).findFirst();
        if (optionalSamplingItemLab.isPresent()) {
            qty = 1;
            SamplingItem samplingItem = new SamplingItem();
            if (optionalSamplingItemLab.isPresent()) {
                samplingItem = optionalSamplingItemLab.get();
                qty = samplingItem.getSampleSize();
            } else {
                qty = 1;
            }
        }
        return qty;
    }

}
